package com.rd.teacher.jichao.day12;

public class TestSync implements Runnable {
    // 假设有100张票
    static int ticketsNum = 100;

    @Override
    public void run() {
        while (true) {
            try {
                Thread.sleep(100);
            } catch (Exception e) {
                e.printStackTrace();
            }
            info();
        }
    }

//    synchronized (obj) {
//        if (ticketsNum <= 0) {
//            System.out.println("票买光了");
//            return;
//        }
//
//        System.out.println(Thread.currentThread().getName() +
//                " 出票：" + ticketsNum);
//        ticketsNum--;
//    }
//

//    private synchronized(this) void info(){
//        if (ticketsNum <= 0) {
//            System.out.println("票买光了");
//            throw new RuntimeException();
//        }
//
//        System.out.println(Thread.currentThread().getName() +
//                " 出票：" + ticketsNum);
//        ticketsNum--;
//    }

    private static synchronized void info() {
        if (ticketsNum <= 0) {
            System.out.println("票买光了");
            throw new RuntimeException();
        }

        System.out.println(Thread.currentThread().getName() +
                " 出票：" + ticketsNum);
        ticketsNum--;
    }

    public static void main(String[] args) {
        TestSync ticket = new TestSync();
        Thread t1 = new Thread(ticket);
        Thread t2 = new Thread(ticket);
        Thread t3 = new Thread(ticket);

        t1.start();
        t2.start();
        t3.start();
    }
}